#!/usr/bin/python3
from openpyxl import load_workbook
import os, gc
from .Base_Plugin import Base_Plugin


class Sheet_Directory_ReIndex(Base_Plugin):
    """重置目录索引插件"""

    def __init__(self, context) -> None:
        super().__init__()
        self.context = context

    def run(self, workspace, source):
        workbook = load_workbook(os.path.join(workspace, source))
        _directory = workbook["目录"]
        for row in _directory.rows:
            if row[0].value == "序号":
                continue
            if row[1].value is None:
                break
            row[0].value = row[0].row - 1

            start_flag = False
            for table_row in workbook[row[2].value].rows:
                if table_row[0].value == "序号":
                    start_flag = True
                    continue

                if not start_flag:
                    continue

                if row[1].value is None:
                    break
                table_row[0].value = table_row[0].row - 3
            self.processed += 1

        saved_name = r"DirectoryReIndexed.xlsx"
        new_path = os.path.join(workspace, saved_name)
        if os.path.exists(new_path):
            os.remove(new_path)
        workbook.save(new_path)
        del workbook
        gc.collect()
        return saved_name
